﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using DGSFramework;
using System.Web.Security;

namespace Framework
{
    public partial class Articles : System.Web.UI.Page
    {
        public DGSFrameworkEntities entity = new DGSFrameworkEntities();
        public List<udv_Categories> allCate = new List<udv_Categories>();
        public List<udv_Articles> allArt = new List<udv_Articles>();
        public List<udv_Users> uUser = new List<udv_Users>();
        public udv_Articles udvArt = new udv_Articles();
        MembershipUser currentUser;

        protected void Page_Load(object sender, EventArgs e)
        {
          
            if (!IsPostBack)
            {
                //if (Session["login"] != null && Session["login"].ToString() == "true")
                //{
                //}
                //else
                //{
                //    string returnUrl = Request.Url.PathAndQuery;
                //    Response.Redirect("/login.aspx?url=" + returnUrl);
                //}

                currentUser = Membership.GetUser();
                if (currentUser != null)
                {                              
                       lblUserName.Text = currentUser.Email;
   
                }else
                {
                    string returnUrl = Request.Url.PathAndQuery;
                    Response.Redirect("/login.aspx?url=" + returnUrl);
                }
                LoadCacheCategory();
               LoadCacheArticle();
                //LoadArticlesMarketNews();
                LoadArticleLang();

            }
        }

        public void LoadPaging(List<udv_Articles> allArticles, ref Controls_PagingControl PagingControl, ref Repeater rpControl, udv_Categories cate)
        {
            double NOProducts = 0;

            PagingControl.pageUrl = ResolveUrl("~/" + DGSFramework.Globals.GetUrl(cate.UrlRewrite, DGSFramework.Globals.GetUrlAspx(cate.UrlRewrite, true) + cate.CateID));

            object objPage = Request.QueryString["page"];
            // check paging
            if (objPage != null)
            {
                int pageindex;
                if (int.TryParse(objPage.ToString(), out pageindex))
                {
                    PagingControl.PageIndex = pageindex;
                }
            }
            else
                PagingControl.PageIndex = 1;

            // check exp must exist
            if (allArticles.Count() == 0)
            {
                return;
            }
            // cal paging
            NOProducts = (double)allArticles.Count() / cate.PagingSize.Value;
            char splitChar = '.';

            if (NOProducts.ToString().Contains('.'))
            { NOProducts++; splitChar = '.'; }

            if (NOProducts.ToString().Contains(','))
            { NOProducts++; splitChar = ','; }

            PagingControl.TotalPage = int.Parse(NOProducts.ToString().Split(splitChar).GetValue(0).ToString());

            if (PagingControl.TotalPage <= 1)
                PagingControl.Visible = false;
            else
                PagingControl.Visible = true;

            allArticles = allArticles.Count() <= cate.PagingSize.Value ? allArticles : allArticles
                .Skip((PagingControl.PageIndex - 1) * cate.PagingSize.Value).Take(cate.PagingSize.Value).ToList();
            rpControl.DataSource = allArticles;
            rpControl.DataBind();
        }
        public void LoadCacheCategory()
        {
            if (Cache["Category"] == null)
            {
                Cache["Category"] = allCate = entity.udv_Categories.ToList();
            }
            else
            {
                allCate = (List<udv_Categories>)Cache["Category"];
            }
        }

        public void LoadCacheArticle()
        {
            if (Cache["Article"] == null)
            {
                Cache["Article"] = allArt = entity.udv_Articles.Include("udv_Categories").ToList();
            }
            else
            {
                allArt = (List<udv_Articles>)Cache["Article"];
            }
        }

        public void LoadArticleLang()
        {
            try
            {
                if (DGSFramework.Globals.IsLanguageVN() == true) 
                {
                    int catevi = 30;
                    var cateVn = allCate.Where(vn => vn.CateID == catevi).FirstOrDefault();
                    var lstArtVn = allArt.Where(avn => avn.udv_Categories.CateID == catevi).OrderBy(avn => avn.DisplayOrder)
                           .ThenByDescending(avn => avn.AddedDate).ToList();
                    rpArticles.DataSource = lstArtVn;
                    rpArticles.DataBind();
                    Controls_PagingControl pagingControl = (Controls_PagingControl)PagingControl1;
                    LoadPaging(lstArtVn, ref pagingControl, ref rpArticles, cateVn);
                }
                else
                {
                    int cateen = 31;
                    var cateEn = allCate.Where(en => en.CateID == cateen).FirstOrDefault();
                    var lstArtEn = allArt.Where(aen => aen.udv_Categories.CateID == cateen).OrderBy(aen => aen.DisplayOrder)
                           .ThenByDescending(aen => aen.AddedDate).ToList();
                    rpArticles.DataSource = lstArtEn;
                    rpArticles.DataBind();
                    Controls_PagingControl pagingControl = (Controls_PagingControl)PagingControl1;
                    LoadPaging(lstArtEn, ref pagingControl, ref rpArticles, cateEn);
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        public void LoadArticlesMarketNews()
        {
            try
            {
                int cat = Int32.Parse(tbIdMarketNews.Value);
                var cateCurrent = allCate.Where(ca => ca.CateID == cat).FirstOrDefault();
                var lstMarketNews = allArt.Where(p => p.udv_Categories.CateID == cat).OrderBy(pr => pr.DisplayOrder)
                           .ThenByDescending(pr => pr.AddedDate).ToList();

                rpArticles.DataSource = lstMarketNews;
                rpArticles.DataBind();
                Controls_PagingControl pagingControl = (Controls_PagingControl)PagingControl1;
               LoadPaging(lstMarketNews, ref pagingControl, ref rpArticles, cateCurrent);
               
            }
            catch (Exception ex)
            {
                throw;
            }
            //if (Request.QueryString["CateID"] != null)
            //{
            //    int cateID;
            //    int.TryParse(Request.QueryString["CateID"].ToString(), out cateID);
            //    var cateCurrent = allCate.Where(ca => ca.CateID == cateID).FirstOrDefault();
            //    if (cateCurrent == null)
            //    {
            //        Response.Redirect(ResolveUrl("~/" + Globals.GetUrl("Errors", "Errors.aspx")));
            //    }
            //    else
            //    {
            //        List<udv_Categories> lstCate = allCate.Where(ca => ca.ParentID == cateCurrent.CateID && ca.IsActive == true).ToList();
            //        if (lstCate.Count > 1)
            //        {
            //            var cateChilds = allCate.Where(ca => ca.ParentID == cateCurrent.CateID && ca.IsActive == true).OrderBy(ca => ca.DisplayOrder).ThenByDescending(ca => ca.AddedDate).ToList();
            //            Controls_PagingControl pagingControl = (Controls_PagingControl)PagingControl1;
            //        }
            //        else
            //        {

            //            List<udv_Categories> lstCateArticle = Globals.LoopGetCategories(ref allCate, cateCurrent.CateID);
            //            lstCateArticle.Add(allCate.Where(ca => ca.CateID == cateCurrent.CateID).FirstOrDefault());
            //            List<udv_Articles> lstArticle = new List<udv_Articles>();
            //            foreach (var item in lstCateArticle)
            //            {
            //                lstArticle = lstArticle.Union(allArt
            //                    .Where(pr => pr.udv_Categories.CateID == item.CateID && pr.IsApproved == true)
            //                    .OrderBy(pr => pr.DisplayOrder)
            //                    .ThenByDescending(pr => pr.AddedDate)).ToList();
            //            }
            //            lstArticle = lstArticle
            //                .OrderBy(pr => pr.DisplayOrder)
            //                .ThenByDescending(pr => pr.AddedDate).ToList();
            //            if (lstArticle.Count == 1)
            //            {
            //                Response.Redirect(ResolveUrl("~/" + Globals.GetUrl(lstArticle.FirstOrDefault().UrlRewrite, Globals.GetUrlAspx(lstArticle.FirstOrDefault().UrlRewrite, false) + lstArticle.FirstOrDefault().ArticleID)));
            //            }
            //            Controls_PagingControl pagingControl = (Controls_PagingControl)PagingControl1;
            //            LoadPaging(lstArticle, ref pagingControl, ref rpArticles, cateCurrent);
            //        }

            //    }
            //}
            //else
            //{
            //    Response.Redirect(ResolveUrl("~/" + Globals.GetUrl("Errors", "Errors.aspx")));
            //}
        }
        protected void btnMemberLogout_Click(object sender, EventArgs e)
        {
            try
            {
                MembershipUser currentUser = Membership.GetUser();
                if (currentUser != null)
                {
                    FormsAuthentication.SignOut();
                    Response.Redirect(Request.RawUrl);
                }
            }
            catch (Exception)
            {

                throw;
            }
        }

    }
}